import { _decorator, Component, Node, Prefab, sys, resources, SpriteFrame, instantiate, Label, input, Input, EventTarget, EventTouch, math } from 'cc'
import { Fruits } from './Fruits'
import { State } from './State'
const { ccclass, property } = _decorator
const eventTarget = new EventTarget()

@ccclass('GameManage')
export class GameManage extends Component {
  @property(Node)
  fruitsBoxNode: Node = null // 水果容器节点
  @property(Label)
  scoreLabel: Label = null // 当前分数文本
  @property(Label)
  maxScoreLabel: Label = null // 最高分数文本
  @property(Prefab)
  fruits: Prefab = null // 水果预制
  @property
  automaticDown: boolean = false // 是否自动下落

  fruitsNode: Node = null // 当前水果节点

  touchIsDown = false // 是否可以触屏放下水果

  currentScore: number = 0 // 当前分数
  maxScore: number = 0 // 最高分数

  gameManageScript: GameManage // 游戏节点脚本

  gameOver = false // 游戏是否结束

  fruitsSpriteFrameArr = []

  start() {
    // 获取历史最高分
    const maxScore = sys.localStorage.getItem('maxScore')
    if (maxScore) this.maxScore = parseInt(maxScore)
    this.setMaxScoreLabel(this.maxScore.toString())

    // 获取游戏节点脚本
    this.gameManageScript = this.node.getComponent(GameManage)

    // 获取水果图片
    for (let i = 0; i < 12; i++) {
      resources.load(`image/l${i}/spriteFrame`, SpriteFrame, (err, spriteFrame) => {
        this.fruitsSpriteFrameArr[i] = spriteFrame
        if (i === 11) {
          this.scheduleOnce(() => {
            if (this.automaticDown) {
              this.schedule(() => {
                this.createdFruits({ x: 360, y: 1200 }, this.setFruitsType(), true, true)
              }, 0.5)
            } else {
              this.createdFruits()
            }

            input.on(Input.EventType.TOUCH_END, this.touch_end, this) // 监听触摸结束
          }, 0.2)
        }
      })
    }
  }

  // 重置游戏
  resetGame(): void {
    if (this.gameOver) return
    console.log('🚀 - resetGame', '游戏结束 重置游戏')
    this.gameOver = true
    // 计算最高分
    if (this.currentScore > this.maxScore) {
      this.maxScore = this.currentScore
      sys.localStorage.setItem('maxScore', this.maxScore.toString())
      this.setMaxScoreLabel(this.maxScore.toString())
    }
    // 重置数据
    this.currentScore = 0
    this.scoreLabel.string = '0'
    this.fruitsNode = null
    this.touchIsDown = false

    // 销毁所有水果
    let fruitsArr: Node[] = this.fruitsBoxNode.children
    let fruitsArrLength = fruitsArr.length
    let speed = 0.05
    fruitsArr.forEach((node, i) => {
      if (i >= fruitsArrLength - 1) {
        // 重新开始游戏
        this.scheduleOnce(() => {
          this.gameOver = false
          if (!this.automaticDown) this.createdFruits()
        }, 3)
      }
      this.scheduleOnce(() => {
        node.destroy()
      }, i * speed)
    })
  }

  // 设置最高分文本
  // score 分数
  setMaxScoreLabel(score: string) {
    this.maxScoreLabel.string = score
    /*  for (let index = 1; index < score.length; index++) {
      this.scheduleOnce(() => {
        this.maxScoreLabel.string = score.slice(0, index + 1)
      }, index * 0.5)
    } */
  }

  // 触摸结束
  touch_end(event: EventTouch): void {
    if (!this.touchIsDown || this.automaticDown) return
    let pos = event.getUIStartLocation()
    this.fruitsNode.getComponent(Fruits).down(pos.x)
    this.touchIsDown = false
    this.scheduleOnce(() => {
      this.createdFruits()
    }, 0.8)
  }

  /* 
    创建水果
    pos:创建位置
    fruitsType:创建水果的类型
    isDown:是否需要下拉掉落
  */
  createdFruits(pos = { x: 360, y: 1200 }, fruitsType: number = this.setFruitsType(), isDown: boolean = true, automaticDown: boolean = false): void {
    if (this.gameOver) return
    let fruitsNode: Node = instantiate(this.fruits)
    if (isDown) this.fruitsNode = fruitsNode
    fruitsNode.setPosition(pos.x, pos.y)
    fruitsNode.getComponent(Fruits).set(this.gameManageScript, this.fruitsSpriteFrameArr[fruitsType], fruitsType, isDown, automaticDown)
    fruitsNode.setParent(this.fruitsBoxNode)
  }

  // 设置水果默认类型
  setFruitsType(): number {
    const arr = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]
    let fruitsType = arr[math.randomRangeInt(0, arr.length)]
    // fruitsType = 1
    return fruitsType
  }

  // 设置是否可以触屏放下水果
  setTouchIsDown(boo: boolean): void {
    this.touchIsDown = boo
  }

  /* 
    水果消除的回调
    fruitsType 消除水果的类型
    pos 生成新的水果的位置
  */
  onFruitFrolic(fruitsType: number, pos): void {
    this.scheduleOnce(() => {
      // 加分
      if (fruitsType === 10) this.currentScore += 1000
      else this.currentScore += fruitsType

      this.scoreLabel.string = this.currentScore.toString()
      // 创建大一级的水果
      this.createdFruits(pos, fruitsType + 1, false)
    }, 0.1)
  }
}
